<?php
declare (strict_types=1);

namespace app\service\logic\common\user;

use app\model\communal\InviteModel;
use app\model\communal\UserModel;
use app\model\communal\UserStatisticsModel;
use app\service\logic\BaseService;

final class InviteService extends BaseService
{
    protected string $modelClassName = 'InviteModel';

    /**
     * 用户邀请逻辑
     *
     * @param $from
     * @param $to
     * @return bool
     */
    public function invite($from, $to)
    {
        // 获取邀请人信息
        $user = UserModel::findOrEmpty($from);
        if ($user->isEmpty()) {
            return false;
        }

        // 用户邀请
        InviteModel::create(['from' => $from, 'to' => $to]);
        return true;
    }

    /**
     * 根据邀请人获取被邀请人的消费累计金额
     *
     * @param $from
     * @return float|int
     */
    public function getAccrueCostByFrom($from)
    {
        $accrueCost = 0;
        $userIds = InviteModel::where('from', $from)->column('to');
        if (!empty($userIds)) {
            $accrueCost = UserStatisticsModel::whereIn('user_id', $userIds)->sum('accrue_cost');
        }

        return $accrueCost;
    }

}
